package kr.co.redcircle.broker.utility;

import kr.co.redcircle.broker.Broker;
import kr.co.redcircle.broker.information.HostInfo;
import kr.co.redcircle.broker.io.BrokerRequest;
import kr.co.redcircle.broker.io.BrokerResult;
import kr.co.redcircle.broker.io.net.Unicast.UnicastNetworkService;
import kr.co.redcircle.broker.registry.Registry;
import net.sf.json.JSONObject;

public class ExecuteBusiness {

	public static BrokerResult execute(HostInfo nameNodeInfo, JSONObject requestParameter) {
		
		HostInfo targetHostInformation = getExecuteTarget(nameNodeInfo);
		
		BrokerRequest invokeRequest = new BrokerRequest(Registry.getCID(), null, requestParameter.getString(Broker.BUSINESS_S), Broker.METHOD_BUSINESS_INVOKE);
		invokeRequest.setParameters(requestParameter);
		String result = syncInvoke(targetHostInformation, invokeRequest);
		System.out.println("ExecuteBusiness.execute.result : " + result);
		return new BrokerResult(result);
	}


	private static HostInfo getExecuteTarget(HostInfo nameNodeInfo) {
		BrokerRequest request = new BrokerRequest(Registry.getCID(), Broker.NAME, Broker.BUSINESS_S, Broker.METHOD_GET_EXECUTE_TARGET);
		String resultFromSyncMethod = syncInvoke(nameNodeInfo.getIp(), nameNodeInfo.getPort(), request);

		JSONObject targetObject = JSONObject.fromObject(resultFromSyncMethod);
		System.out.println("ExecuteBusiness.getExecuteTarget : " + targetObject);
		return new HostInfo(targetObject.getJSONObject(Broker.RESULT));
	}
	
	public static String syncInvoke(HostInfo targetHost, BrokerRequest request) {
		request.setTo(targetHost.getCid());
		System.out.println(targetHost + "," + request);
		return syncInvoke(targetHost.getIp(), targetHost.getPort(), request);
	}
	
	private static String syncInvoke(String nameNodeIp, int nameNodePort, BrokerRequest request) {
		return UnicastNetworkService.sendSync(nameNodeIp, nameNodePort, request.toString());		
	}

}
